<template>
     

  <div class="app-container">
    <div v-if="lange" class="qrCodeContainer" style="width: 450px; height: 50px; display: none; width: 100%">
      <h1 class="title" style="width: 480px; margin-left: 45%; font-size: 17px">{{ $t(`Print.PurchaseInboundList`) }}</h1>
      <div style="width: 95%; margin: auto">
        <div style="display: flex; width: 100%; font-size: 13px; justify-content: space-between">
          <h2 style="font-size: 13px; font-size: 11px">{{ $t(`Print.Manufacturers`) }}:{{ slipNoList3[0]?.vendorName }}</h2>
          <h2 style="margin-left: 50px; font-size: 13px; font-size: 11px">{{ $t(`Print.ArrivalDate`) }}:{{ slipNoList3[0]?.sendDate }}</h2>
          <h2 style="margin-left: 50px; font-size: 13px; font-size: 11px">{{ $t(`Print.InboundOrderNumber`) }}:{{ slipNoList3[0]?.recNo }}</h2>
          <h2 style="margin-left: 50px; font-size: 13px; font-size: 11px">{{ $t(`Print.DeliveryNoteNumber`) }}:{{ slipNoList3[0]?.sendNo }}</h2>
          <h2 style="margin-left: 50px; font-size: 13px; font-size: 11px">{{ $t(`Print.DateOfPrinting`) }}:{{ formatCurrentDateTime(currentDate) }}</h2>
        </div>

        <div style="width: 100%">
          <table style="width: 100%; font-size: 13px">
            <thead>
              <tr>
                <th>{{ $t(`Print.Directives`) }}</th>
                <th>{{ $t(`Print.MaterialColorKey`) }}</th>
                <th>{{ $t(`Print.MaterialName`) }}</th>
                <th>{{ $t(`Print.Specification`) }}</th>
                <th>{{ $t(`Print.Unit`) }}</th>
                <th>{{ $t(`Print.Type`) }}</th>
                <th>{{ $t(`Print.TActualAmountReceivedype`) }}</th>
                <th>{{ $t(`Print.Remark`) }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(iten1, index) in slipNoList3" :key="index">
                <td>{{ iten1.purLot }}</td>

                <td>{{ iten1.mtlColor }}</td>
                <td>{{ iten1.mtlName }}</td>
                <td>{{ iten1.mtlSpec }}</td>
                <td>{{ iten1.mtlUnit }}</td>

                <td>{{ iten1.slipType }}</td>
                <td>{{ iten1.sendQty }}</td>

                <td>{{ iten1.remark }}</td>
                <!-- 更多的数据单元格 -->
              </tr>
              <!-- 更多的行 -->
            </tbody>
            <!-- 可选的 tfoot 部分 -->
          </table>

          <!-- <Table :tableHeader="tableHeader5" :tableData="slipNoList" /> -->
        </div>
        <div style="padding: 0; margin: 0; font-size: 11px; line-height: normal; font-weight: normal; font-family: inherit; color: inherit">
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">{{ $t(`Print.Illustrate`) }}</h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">
            {{ $t(`Print.WhenDeliveringYouMustBringTheDeliveryNoteToThePlaceToPrintTheWarehousingOrderTheGoodsArriveAtTheOrderIfYouDoNotBringTheOrderWillBeDelayedThankYouForYourCooperation`) }}
          </h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">
            {{ $t(`Print.TheSupplyOrderMustContainInstructionSheetMaterialColorMaterialNameSpecificationQuantityUnitUnitPriceAmountIncludingTaxOrExclusiveDeliveryPeriod`) }}
          </h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">{{ $t(`Print.AccordingToTheConfirmedSamplesAndTestResultsWeAreWillingToAcceptTheBuyersReturnOrDiscountWhenTheQualityIsPoor`) }}</h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">
            {{ $t(`Print.PleaseDliverTheGoodsDuringWorkingHoursWillNotReceiveTheGoodsDuringTheOffdutyHoursIfThereAreSpecialCircumstancesPleaseContactThePurchasingDepartmentOfTheSupplyCenterTankYou`) }}
          </h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">
            {{ $t(`Print.IfTheDeliveryIsDelayed005OfTheTotalOrderPriceIsUsedAsLiquidatedDamagesAndTheSupplierShallBearAllTheLossesCausedByTheDeliveryTimeAndPoorQuality`) }}
          </h3>
          <h3 style="margin: 0; padding: 0; font-size: 7px !important">TEL:18296370303</h3>
        </div>

        <div style="display: flex; justify-content: space-between; width: 85%; font-size: 17px; width: 80%; margin: auto">
          <h2 style="font-size: 13px">{{ $t(`Print.Attn`) }}:</h2>
          <h2 style="font-size: 13px">{{ $t(`Print.Reviewers`) }}:</h2>
          <h2 style="font-size: 13px">{{ $t(`Print.Manufacturers`) }}:</h2>
          <h2 style="font-size: 13px">{{ $t(`Print.ReceiptInspector`) }}:</h2>
        </div>
      </div>
    </div>

    <div v-else class="qrCodeContainer" style="width: 450px; height: 50px; display: none; width: 100%">
      <h1 class="title" style="width: 480px; margin-left: 35%; font-size: 17px">PHIẾU XUẤT KHO- NGUYÊN LIỆU </h1>
      <h1 class="title" style="width: 480px; margin-left: 42%; font-size: 17px">{{ formattedDate }}</h1>
      <h1 class="title" style="width: 480px; margin-left: 38%; font-size: 17px">Số 编号: {{slipNoList3[0]?.recNo}}</h1>

      <h1 class="title" style="width: 480px; font-size: 17px">Họ và tên người giao:</h1>
      <h1 class="title" style="width: 480px; font-size: 17px">Theo Hợp Đồng gia công  số :</h1>
      <h1 class="title" style="width: 480px; font-size: 17px">Theo Tờ khai hải quan số:</h1>
      <h1 class="title" style="width: 480px; font-size: 17px">Nhập tại kho:</h1>

      <div style="width: 95%; margin: auto">
       

        <div style="width: 100%">
          <table style="width: 100%; font-size: 13px">
            <thead>
              <tr>
                <th>STT</th>
                <th>Mã NL</th>
                <th>Tên, nhãn hiệu, quy cách hàng hóa</th>
                <th>Mã số thu mua</th>
                <th>Đơn vị tính</th>
                <th>Số lượng</th>
                <th>Ghi Chú</th>
              </tr>
            </thead>
            <tbody>
              <tr >
                <td></td>
                <tr style="display: grid; grid-template-columns: 1fr 1fr 1fr;">
                    <th style="border-right: 1px solid;">Mã HQ</th>
                    <th style="border-right: 1px solid;">Mã kho</th>
                    <th>物料编码</th>
                  </tr>
                <td></td>
                <td></td>
                <td></td>
                <tr style="display: grid; grid-template-columns: 1fr 1fr;">
                    <th style="border-right: 1px solid;">Mã HQ</th>
                    <th style="border-right: 1px solid;">Mã kho</th>
                  </tr>
                <!-- <td>Thực nhập</td>
                <td>Theo chứng từ</td> -->
                <!-- 更多的数据单元格 -->
              </tr>
              <tr v-for="(iten1, index) in slipNoList3" :key="index">

                <td>{{ index + 1 }}</td>

                <tr style="display: grid; grid-template-columns: 1fr 1fr 1fr;">
                    <th style="border-right: 1px solid;">{{ iten1.mtlNoHg }}</th>
                    <th style="border-right: 1px solid;">{{ iten1.mtlNoHg }}</th>
                    <th>{{ iten1.mtlNo }}</th>
                  </tr>
                  
                  <td>{{ iten1.mtlName }} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ iten1.mtlNameEng
 }}</td>

                <td>{{ iten1.purNo }}</td>
                <td>{{ iten1.mtlUnit}}</td>
                <tr style="display: grid; grid-template-columns: 1fr 1fr;">
                    <th style="border-right: 1px solid;">{{ iten1.sendQty }}</th>
                    <th style="border-right: 1px solid;">{{ iten1.sendQty }}</th>
                  </tr>

                <td>{{ iten1.remark }}</td>
                <!-- 更多的数据单元格 -->
              </tr>
              <!-- 更多的行 -->
            </tbody>
            <!-- 可选的 tfoot 部分 -->
          </table>

          <!-- <Table :tableHeader="tableHeader5" :tableData="slipNoList" /> -->
        </div>
        <!-- <h3 style="margin-left: 650px; font-size: 21px !important">{{ $t(`Print.TotalDispatch`) }}:{{ numberList.toFixed(2) }}</h3> -->
        <h3 style="margin-left: 850px; font-size: 13px !important">{{ formattedDate }}</h3>

        <div style="display: flex; justify-content: space-between; width: 85%; font-size: 17px; width: 80%; margin: auto">
          <h2 style="font-size: 13px">Người lập phiếu:</h2>
          <h2 style="font-size: 13px">Người nhận hàng :</h2>
          <h2 style="font-size: 13px">Thủ kho:</h2>
          <h2 style="font-size: 13px">
            <h1 style="font-size: 13px">Kế toán trưởng:</h1>
          </h2>
        </div>
      </div>
    </div>

  <Find :OriginalFilter="{ static: true }" :formList="formList1" @findClicked="findData" @Launchform="Launchform"
    @clickNumber="clickNumber" />

  <el-card style="margin-top: 10px;" shadow="always" :body-style="{ padding: '5px' }">
    <div style="display: flex;">
      <div style="width: 90%;">
        <h1>{{ $t(`Print.PickingDetails`) }}</h1>
        <Table @checkboxChange="change" @currentRow1="dbClickTableRow" :isLoading="isLoading1"
            @currentRow="clicktogetdata" :tableHeader="tableHeader"
          :tableData="MaterialRequisitionDetailsMethodsTableDateList.dtos" :TableHeight="100" :outTableHeight="130" />
      </div>
      <div style="width: 10%;margin-left: 10px;">
        <h1>{{ $t(`Print.DetailedInquiryOfActualInventions`) }}</h1>
        <Table :isLoading="isLoading3" :summaryData="summaryData1" summary :tableHeader="tableHeader1"
          :tableData="ActualInventionMethodsTableDateList.dtos" :TableHeight="100" :outTableHeight="130" />

      </div>
    </div>
    <div style="display: flex;justify-content: space-between;">
      <div style="display: flex;width: 40%;flex-wrap: wrap;">
        <p style="margin-top: 10px;">
          <span class="mr10">{{ $t(`Print.MaterialName`) }}</span>
          <el-input class="mr55" placeholder="" size="small" clearable @change="" style="width: 495px;"
            v-model="TheTotalNumberIsDisplayed.mtlName" />
        </p>

        <p style="margin-top: 5px;">
          <span class="mr10">{{ $t(`Print.TheItemCode`) }}</span>
          <el-input placeholder="" size="small" clearable @change="" style="width: 120px;"
            v-model="TheTotalNumberIsDisplayed.mtlNo" />
          <span class="mr10">{{ $t(`Print.FeedOrderNumber`) }}</span>
          <el-input placeholder="" size="small" clearable @change="" style="width: 120px;"
            v-model="TheTotalNumberIsDisplayed.slipNo" />
          <span class="mr10">{{ $t(`Print.Remark`) }}</span>
          <el-input class="mr55" placeholder="" size="small" clearable @change="" style="width: 120px;"
            v-model="TheTotalNumberIsDisplayed.remark" />
        </p>
      </div>
      <div style="display: flex;width: 40%;flex-wrap: wrap;">

        <p>
        <h1 style="font-size: 14px;margin-left: 10px;">{{ $t(`Print.AlternativeaterialInformation`) }}</h1>
        <span class="mr10">{{ $t(`Print.MaterialColorKey`) }}</span>
        <el-input placeholder="" size="small" clearable @change="" style="width: 100px;"
          v-model="TheTotalNumberIsDisplayedKlt1.mtlColor" />
        <span class="mr10">{{ $t(`Print.MaterialName`) }}</span>
        <el-input placeholder="" size="small" clearable @change="" style="width: 275px;"
          v-model="TheTotalNumberIsDisplayedKlt1.mtlName" />
        </p>

        <p style="margin-top: 5px;">

          <span class="mr10">{{ $t(`Print.Specification`) }}</span>
          <el-input placeholder="" size="small" clearable @change="" style="width: 130px;"
            v-model="TheTotalNumberIsDisplayedKlt1.mtSpace" />
          <span class="mr10">{{ $t(`Print.Unit`) }}</span>
          <el-input placeholder="" size="small" clearable @change="" style="width: 120px;"
            v-model="TheTotalNumberIsDisplayedKlt1.mtUnint" />
          <span class="mr10">{{ $t(`Print.InventoryLevels`) }}</span>
          <el-input placeholder="" size="small" clearable @change="" style="width: 120px;"
            v-model="TheTotalNumberIsDisplayedKlt1.stkQty" />
        </p>
      </div>

    </div>
    <PageModule :PageData="{ total }" @pageChange="handleSizeChangeT" @pageSizeChange="handleCurrentChangeT" />
  </el-card>

  <el-drawer v-model="drawer1" :direction="'ttb'" size="small" :with-header="false">
    <span @click="drawer1 = false" style="float: right;cursor: pointer;color: rgb(7, 7, 7);">X</span>
    <h1>{{ $t(`Print.QueryCondition`) }}</h1>
    <Find :OriginalFilter="{ static: true }" :searchImg="false" :formList="formList2" @findClicked="findData1"
      @Launchform="Launchform1" />
    <h1 style="margin-top: 10px;">{{ $t(`Print.InventoryDetailsInquiry`) }}</h1>
    <Table @currentRow="clicktogetdata1" style="width: 40%;" :tableHeader="tableHeader2"
      :tableData="ActualInventionTableDateList.dtos" :TableHeight="100" :outTableHeight="50" :isLoading="isLoading" />
    <PageModule :PageData="{ total: totalT }" @pageChange="handleSizeChange" @pageSizeChange="handleCurrentChange" />
  </el-drawer>

  <el-drawer v-model="drawer2" :direction="'ttb'" size="small" :with-header="false">
    <span @click="drawer1 = false" style="float: right;cursor: pointer;color: rgb(7, 7, 7);">X</span>
    <h1>{{ $t(`Print.QueryCondition`) }}</h1>
    <Find :OriginalFilter="{ static: true }" :searchImg="false" :formList="formList3" @Launchform="Launchform2" />
    <h1 style="margin-top: 10px;">{{ $t(`Print.MaterialSubstitutionInquiry`) }}</h1>
    <Table style="width: 80%;" :tableHeader="tableHeader3"
      :tableData="MaterialSubstitutionQueryMethodsTableDateList.dtos" :TableHeight="100" :outTableHeight="50"
      :isLoading="isLoading" />
    <PageModule :PageData="{ total: totalTl }" @pageChange="handleSizeChangel" @pageSizeChange="handleCurrentChangel" />
  </el-drawer>

  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import LoginWork from '@/utils/LoginWork'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'MaterialRequisitionConfirmation'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { ref, onMounted } from 'vue'

import {MaterialRequisitionConfirmationDelete,MaterialRequisitionConfirmation,MaterialSubstitutionProcessing, AcquisitionSortKle, Department, MaterialRequisitionDetails, ActualInvention, substituteMaterial, AcquisitionSort, BlockDeletion, MaterialSubstitutionQuery } from '@/api/WarehouseDepartment/FactoryStorage/MaterialRequisitionConfirmation'
import type { MaterialSubstitutionQueryInterface, MaterialSubstitutionQueryParms, MaterialRequisitionDetailsParms, MaterialRequisitionDetailsInterface, substituteMaterialInterface, substituteMaterialParms, ActualInventionInterface } from '@/api/WarehouseDepartment/FactoryStorage/MaterialRequisitionConfirmation'
import { ElMessage, ElMessageBox, } from 'element-plus'
const date = new Date();
const formattedDate = date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0');
const RedrawTheLabelMethodsParms = ref('')
const slipNoList3 = ref<any>([])

// 日期
const formatCurrentDateTime = (date?: Date) => {
  const year = date!.getFullYear()
  const month = String(date!.getMonth() + 1).padStart(2, '0') // 使用padStart确保月份是两位数
  const day = String(date!.getDate()).padStart(2, '0') // 使用padStart确保日期是两位数
  const hours = String(date!.getHours()).padStart(2, '0') // 小时
  const minutes = String(date!.getMinutes()).padStart(2, '0') // 分钟
  const seconds = String(date!.getSeconds()).padStart(2, '0') // 秒

  // 返回格式化的日期时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 删除
const MaterialRequisitionConfirmationDeleteParms = ref('')

const MaterialRequisitionConfirmationDeleteMethods = async () => {
  try {
    const res = await MaterialRequisitionConfirmationDelete(MaterialRequisitionConfirmationDeleteParms.value) 
    if(res.code === 200) {
     
      JMessage.success(res.message)
      MaterialRequisitionDetailsMethods() 
    }else{
      JMessage.error(res.message)
    }
  }catch (error) {
    JMessage.error('删除失败') 
  } 
}

const handleCloseMateriaLKlc = (_done?: () => void) => {
  if (MaterialRequisitionConfirmationDeleteParms.value.length === 0) {
    JMessage.warning('请勾选需要删除的数据')
  } else {
    ElMessageBox.confirm('确认要删除数据吗?')
      .then(async () => {
        MaterialRequisitionConfirmationDeleteMethods()
      })
      .catch(() => {})
  }
}

const MaterialRequisitionConfirmationParms = ref('')

const TheTotalNumberIsDisplayedKlt1 = ref({
  mtlName:'',

  mtlColor:'',
  mtSpace:'',
  mtUnint:'',
  stkQty:''
})

const MaterialRequisitionConfirmationMethods = async () => {
  try {
    const res = await MaterialRequisitionConfirmation(MaterialRequisitionConfirmationParms.value)
    if(res.code === 200) {
     if(res.data !== null){
    TheTotalNumberIsDisplayedKlt1.value.mtlName = res.data.mtlName
    TheTotalNumberIsDisplayedKlt1.value.mtlColor = res.data.mtlColor
    TheTotalNumberIsDisplayedKlt1.value.mtSpace = res.data.mtSpace
    TheTotalNumberIsDisplayedKlt1.value.mtUnint = res.data.mtUnint
    TheTotalNumberIsDisplayedKlt1.value.stkQty = res.data.stkQty
     }else{
      TheTotalNumberIsDisplayedKlt1.value.mtlName = ''
    TheTotalNumberIsDisplayedKlt1.value.mtlColor = ''
    TheTotalNumberIsDisplayedKlt1.value.mtSpace = ''
    TheTotalNumberIsDisplayedKlt1.value.mtUnint = ''
    TheTotalNumberIsDisplayedKlt1.value.stkQty = ''
     }
   
    }else{
      JMessage.error(res.message)
    }
  } catch (error) {
    JMessage.error('获取替代材料信息失败')
  }
}


// 物料替代
const MaterialSubstitutionProcessingParms = ref<any>({
    mtlColor:"",
    mtlName:"",
    mtlNo:"",
    mtlSpec:"",
    mtlUnit:""
})

const MaterialSubstitutionProcessingId = ref('')

const MaterialSubstitutionProcessingMethods = async () => {
  try {
    const res = await MaterialSubstitutionProcessing(MaterialSubstitutionProcessingParms.value,MaterialSubstitutionProcessingId.value)
    if(res.code === 200) {
      MaterialRequisitionDetailsMethods()
      JMessage.success(res.message)
    }else{
      JMessage.error(res.message)
    }
  } catch (error) {
    JMessage.error('操作失败')
  }
}

const formList1 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入领料单号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '领料日期',
    dateValue: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '部门',
    selectLabel: '',
    selectOptions: [],
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '领料类型',
    selectLabel: '',
    selectOptions: [
      { optionKey: 1, optionValue: '指令资料', optionLabel: '指令资料' },
      { optionKey: 2, optionValue: '补料领料', optionLabel: '补料领料' },
      { optionKey: 3, optionValue: '非指令领料', optionLabel: '非指令领料' },
    ],
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '分类',
    selectLabel: '',
    selectOptions: [],
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: ''
  },
  {
    type: 'radio',
    checkboxLabel: '全部未发',
    checked: true,
    label: '1'
  },
  {
    type: 'radio',
    checkboxLabel: '部分未发',
    checked: true,
    label: '2'
  },
  {
    type: 'radio',
    checkboxLabel: '全部已发',
    checked: true,
    label: '3'
  },
  {
    type: 'radio',
    checkboxLabel: '全部',
    checked: true,
    label: '4'
  },
  {
    type: 'button',
    checkboxLabel: '实发批处理',
  },
  {
    type: 'button',
    checkboxLabel: '材料代替查询',
  },
  {
    type: 'button',
    checkboxLabel: '替代物料删除',
  },
  {
    type: 'button',
    checkboxLabel: '打印出库单',bgColor:'#1890FF',
  },
  {
    type: 'button',
    checkboxLabel: '置空',bgColor:'#1890FF',
  },

])

const formList2 = ref([
  {
    type: 'select',
    selectValue: '',
    selectP: '分类',
    selectLabel: '',
    selectOptions: [],
  },
  {
    type: 'input',
    inputPlaceholder: '材料名称',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '确认',
  },
  {
    type: 'button',
    checkboxLabel: '置空',bgColor:'#1890FF',
  },
])

const formList3 = ref([
  {
    type: 'input',
    inputPlaceholder: '领料单号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '材料名称(替代前)',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '材料名称(替代后)',
    inputValue: ''
  },
])

const drawer1 = ref(false)

const drawer2 = ref(false)

const isLoading3 = ref(true)

const change = async (row: any, prop: any) => {
  const { slipNo, mtlNo, lotNo } = prop
  const result = await BlockDeletion(slipNo, mtlNo, lotNo)
  if (result.code === 200) {
    MaterialRequisitionDetailsMethods()
    JMessage.success(result.message)
  } else {
    JMessage.error(result.message)
  }

}

// 修改
const inputChange1 = (row:any) => {
  // console.log(row)
  // if(row.avtQty === ''){
  //   row.actQty = ''
  // }else{
  //   row.actQty = Number(row.avtQty)
  // }
  
}

const confirmChange = async (row: any) => {

  let array = MaterialRequisitionDetailsMethodsTableDateList.value.dtos.filter((item:any) => item.avtQty !== undefined && item.avtQty !== '')
  if(array.length === 0){
    return JMessage.warning('请填写实发数量')
  }
  array = array.map((item:any) => {
    item.actQty = Number(item.avtQty)
    item.qty = Number(item.avtQty)
    item.slipDate = item.slipDate2
    return item
  })
  
  
  const result = await LoginWork.put<any, any>('/pcFactorStockQuery/DrawActPro', array)
  if (result.code === 200) {
    ActualInventionMethods()
    MaterialRequisitionDetailsMethods()
    JMessage.success(result.message)
  } else {
    JMessage.error(result.message)
  }
}

// 双击
const mtlNoValue = ref('')

const rowValue = ref()

const dbClickTableRow = (row?:any,blum?:string) => {
  MaterialSubstitutionProcessingId.value = row.id
  if(blum === 'mtlName'){
    // ActualInventionTableDateListParms.value.mtlName = row.mtlName
    formList2.value[1].inputValue = row.mtlName
    substituteMaterialMethods()
    AcquisitionSortMethods()
  rowValue.value = row
  if (row) {
    drawer1.value = true;
    MaterialRequisitionDetailsMethodsTableDateList.value.dtos = MaterialRequisitionDetailsMethodsTableDateList.value.dtos.map((item: any) => {
      // if (item === rowValue.value) {
      //   item.mtlNo2 = mtlNoValue.value;
      // }
      return item;
    });
    mtlNoValue.value = ''
  }
  }
   if(blum === 'avtQty'){
    row.avtQty = row.reqQty - row.actQty
    row.slipDate2 = formatCurrentDate(currentDate.value)
  }
};

const currentDate = ref(new Date());

const formatCurrentDate = (date: any) => {  
  const year = date.getFullYear();  
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份加 1 并格式化为双位  
  const day = String(date.getDate()).padStart(2, '0'); // 日期格式化为双位  
  return `${year}-${month}-${day}`;  
};


const clicktogetdata1 = (row: any) => {
  const { mtlNo, mtlColor2, mtlName2, mtSpace2, mtUnint2, stkQty2,mtlNo2,mtlUnit2,mtlSpec2 } = row;
  mtlNoValue.value = mtlNo;
    MaterialSubstitutionProcessingParms.value.mtlColor = mtlColor2
    MaterialSubstitutionProcessingParms.value.mtlName = mtlName2
    MaterialSubstitutionProcessingParms.value.mtlNo = mtlNo2
    MaterialSubstitutionProcessingParms.value.mtlSpec = mtlSpec2
    MaterialSubstitutionProcessingParms.value.mtlUnit = mtlUnit2

  if (mtlColor2 !== '' || mtlName2 !== '' || mtSpace2 !== '' || mtUnint2 !== '' || stkQty2 !== '') {
    TheTotalNumberIsDisplayedKlt.value.mtlName = mtlName2
    TheTotalNumberIsDisplayedKlt.value.mtlColor = mtlColor2
    TheTotalNumberIsDisplayedKlt.value.mtSpace = mtSpace2
    TheTotalNumberIsDisplayedKlt.value.mtUnint = mtUnint2
    TheTotalNumberIsDisplayedKlt.value.stkQty = stkQty2


  }

  const updatedDtos = MaterialRequisitionDetailsMethodsTableDateList.value.dtos.map((item: any) => {
    // 使用 Object.assign 或扩展运算符来合并对象，创建新的对象
    if (rowValue.value === item) {
      const updatedItem = Object.assign({}, item, row);
      return updatedItem;
    }
    return item
  });
  // 现在 updatedDtos 包含了所有原始对象和新的合并对象，不会影响原始数组
  // MaterialRequisitionDetailsMethodsTableDateList.value.dtos = updatedDtos;
};


// 回显总数居
const TheTotalNumberIsDisplayed = ref({
  mtlName: '',
  mtlNo: '',
  slipNo: '',
  remark: ''
})

const TheTotalNumberIsDisplayedKlt = ref<any>({
  mtlColor: '',
  mtlName: '',
  mtSpace: '',
  mtUnint: '',
  stkQty: '',
})

// 分类获取
const AcquisitionSortKleMethods = async () => {
  const result = await AcquisitionSortKle()
  let NewArray = result.reduce((arr: any, item: any) => {
    if (item.typeNo && item.typeName) { // 只添加非空的 typeName 和 typeNo
      arr.push(item.typeNo + " " + item.typeName);
    }
    return arr;
  }, []);
  formList1.value[5].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
}

// 材料替代查询
const MaterialSubstitutionQueryMethodsTableDateList = ref<MaterialSubstitutionQueryInterface>({
  dtos: []
})

const MaterialSubstitutionQueryMethodsParms = ref<MaterialSubstitutionQueryParms>({
  mtlName1: '',
  mtlName2: '',
  pageNum: 1,
  pageSize: 40,
  slipNo: ''
})

const MaterialSubstitutionQueryMethods = async () => {
  const result = await MaterialSubstitutionQuery(MaterialSubstitutionQueryMethodsParms.value)
  MaterialSubstitutionQueryMethodsTableDateList.value.dtos = result.dtos
  totalTl.value = result.total!
}

// 获取分类
const isLoading = ref(false)

const AcquisitionSortMethods = async () => {
  const result = await AcquisitionSort()
  let NewArray = result.reduce((arr: any, item: any) => {
    if (item.typeNo && item.typeName) { // 只添加非空的 typeName 和 typeNo
      arr.push(item.typeNo + " " + item.typeName);
    }
    return arr;
  }, []);
  formList2.value[0].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
}

// 替代物料查询
const ActualInventionTableDateList = ref<substituteMaterialInterface>({
  dtos: []
})

const ActualInventionTableDateListParms = ref<substituteMaterialParms>({
  mtlName: '',
  mtlTypeNo: '',
  pageNum: 1,
  pageSize: 40
})

const substituteMaterialMethods = async () => {
  isLoading.value = true
  const result = await substituteMaterial(ActualInventionTableDateListParms.value)
  ActualInventionTableDateList.value.dtos = result.dtos.map((item: any, index: number) => {
    // 创建一个新对象，修改属性名
    const newItem: any = {};
    for (const key in item) {
      newItem[key + '2'] = item[key];
    }
    return newItem;
  });

  totalT.value = result.total!
  isLoading.value = false
}

// 实发明细查询
const ActualInventionMethodsTableDateList = ref<ActualInventionInterface>({
  dtos: [],
  sum: 0,
})

interface summaryDataType {
  index: number,
  num: number | undefined
}

const summaryData1 = ref<summaryDataType[]>([
  {
    index: 1,
    num: 0
  }
])

const mtlNo1 = ref('')

const slipNo1 = ref('')

const lotNo1 = ref('')


const ActualInventionMethods = async () => {
  isLoading3.value = true
  const result = await ActualInvention(mtlNo1.value)
  ActualInventionMethodsTableDateList.value.dtos = result.dtos
  ActualInventionMethodsTableDateList.value.sum = result.sum
  summaryData1.value[0].num = result.sum
  isLoading3.value = false
}

// 领料明细
const rouLableValue = ref()

const clicktogetdata = (row: any) => {
  slipNoList3.value = MaterialRequisitionDetailsMethodsTableDateList.value.dtos.filter((item: any) => item.slipNo === row.slipNo)
  rouLableValue.value = row
  const { mtlNo, mtlName2, slipNo, mtlName, remark, mtlColor2, mtSpace2, mtUnint2, stkQty2, lotNo,id } = row
  mtlNo1.value = id
  slipNo1.value = slipNo
  lotNo1.value = lotNo
  MaterialRequisitionConfirmationParms.value = id
  MaterialRequisitionConfirmationDeleteParms.value = id
  ActualInventionMethods()

  MaterialRequisitionConfirmationMethods()

  TheTotalNumberIsDisplayed.value.mtlName = mtlName
  TheTotalNumberIsDisplayed.value.mtlNo = mtlNo
  TheTotalNumberIsDisplayed.value.remark = remark
  TheTotalNumberIsDisplayed.value.slipNo = slipNo

  // if (mtlColor2 !== '' || mtlName2 !== '' || mtSpace2 !== '' || mtUnint2 !== '' || stkQty2 !== '') {
  //   TheTotalNumberIsDisplayedKlt.value.mtlName = mtlName2
  //   TheTotalNumberIsDisplayedKlt.value.mtlColor = mtlColor2
  //   TheTotalNumberIsDisplayedKlt.value.mtSpace = mtSpace2
  //   TheTotalNumberIsDisplayedKlt.value.mtUnint = mtUnint2
  //   TheTotalNumberIsDisplayedKlt.value.stkQty = stkQty2
  // }
}

const MaterialRequisitionDetailsMethodsParms = ref<MaterialRequisitionDetailsParms>({
  deptName: '',
  deptNo: '',
  lotNo: '',
  mtlName: '',
  mtlTypeNo: '',
  pageNum: 1,
  pageSize: 40,
  slipDateEnd: '',
  slipDateStart: '',
  slipNo: '',
  slipType: '',
  userType: 1
})

const MaterialRequisitionDetailsMethodsTableDateList = ref<MaterialRequisitionDetailsInterface>({
  dtos: []
})

const isLoading1 = ref(false)

const MaterialRequisitionDetailsMethods = async () => {
  isLoading1.value = true
  const result = await MaterialRequisitionDetails(MaterialRequisitionDetailsMethodsParms.value)
  MaterialRequisitionDetailsMethodsTableDateList.value.dtos = result.dtos.map((item: any) => {
    if (item.cancelFlag === 'Y') {
      item.cancelFlag = true
      item.change = ''
    }
    if (item.reqQty === item.actQty) {
      item.backgroundColor = '#3FFF38'
    }
    if (item.backgroundColor) {
      item.change = ''
    } else {
      item.change = 'Y'
      item.disableConfirm = true
    }

    return item
  })
  total.value = result.total!
  if (result.dtos.length > 0) {
    const { mtlNo, slipNo, mtlName, remark, lotNo,id } = result.dtos[0]
    mtlNo1.value = id
    slipNo1.value = slipNo
    MaterialRequisitionConfirmationParms.value = slipNo
    TheTotalNumberIsDisplayed.value.mtlName = mtlName
    TheTotalNumberIsDisplayed.value.mtlNo = mtlNo
    TheTotalNumberIsDisplayed.value.remark = remark as string
    TheTotalNumberIsDisplayed.value.slipNo = slipNo
    lotNo1.value = lotNo
    ActualInventionMethods()
  }
  isLoading1.value = false
}

// 部门
const EvaluatesTheArrayReturnValue = (ArrayList: any) => {
  return ArrayList.map((item: any, index: any) => {
    return {
      optionKey: index,
      optionValue: item,
      optionLabel: item
    }
  })
}

const gainDepartment = async () => {
  const result = await Department()
  let NewArray = result.reduce((arr: any, item: any) => {
    if (item.deptName && item.deptNo) { // 只添加非空的 typeName 和 typeNo
      arr.push(item.deptNo + " " + item.deptName);
    }
    return arr;
  }, []);
  formList1.value[3].selectOptions = EvaluatesTheArrayReturnValue(NewArray)
}
const printQRCode = () => {
  const qrCodeContainer = document.querySelector<any>('.qrCodeContainer')
  if (qrCodeContainer) {
    // 临时显示 .qrCodeContainer 以获取其内容
    qrCodeContainer.style.display = 'block'

    const printWindow = window.open('', '_blank')
    printWindow!.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>打印指令领料作业</title>
          <link rel="stylesheet" type="text/css" href="print.css" media="print">
          <style>
            body, html {
              margin: 0;
              padding: 0;
            }
            @page {
              size: auto; 
              margin: 3mm;
            }
            @media print {
                /* 打印时的样式 */
             
                
                /* 其他打印样式 */
            }
            h2 {
                    margin-left: initial; /* 或者设置适合打印的左边距 */
                    page-break-inside: avoid; /* 避免在h2元素内部分页 */
                }
            h3{
              font-size:13px;
            }
               

            table, th, td {
                    border: 1px solid black; 
                    border-collapse: collapse; 
                    text-align: center;
                  }
                  th, td {
                    padding: 5px; /* 设置内边距 */
                    text-align: left; /* 设置文本对齐方式 */
                    text-align: center;
                    font-size:11px
                  }
                  .double-line {
                    border-top: 2px dashed red; 
                    border-bottom: 2px dashed red; 
                    text-align: center;
                  }
           
            /* 可以在这里添加更多自定义的打印样式 */
          </style>
        </head>
        <body>
    `)

    // 将 .qrCodeContainer 的内容复制到打印窗口的 body 中
    const cloneContainer = qrCodeContainer.cloneNode(true)
    printWindow!.document.body.appendChild(cloneContainer)

    printWindow!.document.write(`
        </body>
      </html>
    `)
    printWindow!.document.close()

    // 开始打印
    printWindow!.print()

    // 打印完成后，可以恢复 .qrCodeContainer 的原始显示状态
    qrCodeContainer.style.display = 'none'
  }
}
const lange = ref(false)
const findData = (find: any) => {
  if (find === '打印出库单') {
    const lang = localStorage.getItem('language')
    if(lang === 'vi'){
      lange.value = false
    }else{
      lange.value = true
    }
    if (slipNoList3.value.length === 0) {
      JMessage.warning('请点击需要打印的数据')
    }else{
      printQRCode()
    }
  
   
  }
  if(find === '替代物料删除'){
    handleCloseMateriaLKlc()
  }
  if (find === '材料代替查询') {
    MaterialSubstitutionQueryMethods()
    drawer2.value = true
  }
  if (find === '置空') {
    clearFormList1()
  }
  if (find === '实发批处理') {
    if (rouLableValue.value) {
      if (rouLableValue.value.avtQty === undefined) {
        JMessage.warning('实发量必须输入')
      } else if(rouLableValue.value.reqQty - rouLableValue.value.actQty - rouLableValue.value.avtQty < 0){
        ElMessage.warning('已超量')
      } else {
        
        confirmChange(rouLableValue.value)
      }

    } else {
      JMessage.warning('请选择需实发批处理的数据')
    }

  }
}

// 统一调用接口
const interAceFunct = () => {
  // 部门
  gainDepartment()

  MaterialRequisitionDetailsMethods()

  AcquisitionSortKleMethods()

  
}

onMounted(() => {
  interAceFunct()
  const lang = localStorage.getItem('language')
  if (lang === 'vi') {
    lange.value = false;
  } else {
    lange.value = true;
  }
  
})

// 分页器
const total = ref(0)

const handleSizeChangeT = (val: number) => {
  MaterialRequisitionDetailsMethodsParms.value.pageNum = val
  MaterialRequisitionDetailsMethods()
}

const handleCurrentChangeT = (val: number) => {
  MaterialRequisitionDetailsMethodsParms.value.pageSize = val
  MaterialRequisitionDetailsMethods()
}

// 分页器
const totalT = ref(0)

const handleSizeChange = (val: number) => {
  ActualInventionTableDateListParms.value.pageNum = val
  substituteMaterialMethods()
}

const handleCurrentChange = (val: number) => {
  ActualInventionTableDateListParms.value.pageSize = val
  substituteMaterialMethods()
}

// 分页器
const totalTl = ref(0)

const handleSizeChangel = (val: number) => {
  MaterialSubstitutionQueryMethodsParms.value.pageNum = val
  MaterialSubstitutionQueryMethods()
}

const handleCurrentChangel = (val: number) => {
  MaterialSubstitutionQueryMethodsParms.value.pageSize = val
  MaterialSubstitutionQueryMethods()
}

const tableHeader = ref([
  {
    label: '领料类型',
    prop: 'slipType',
    change: true
  },
  {
    label: '海关编码',
    prop: 'mtlNoHg',
    change: true
  },
  {
    label: '指令',
    prop: 'lotNo',
    change: true
  },
  {
    label: '部门名称',
    prop: 'deptName',
    change: true
  },
  {
    label: '规格',
    prop: 'mtlSpec',
    width: '55',
    change: true
  },
  {
    label: '单位',
    prop: 'mtlUnit',
    width: '55',
    change: true
  },
  {
    label: '领料单号',
    prop: 'slipNo',
    change: true
  },
  {
    label: '领料日期',
    prop: 'slipDateShow',
    change: true
  },
  {
    label: '材料颜色',
    prop: 'mtlColor',
    change: true
  },
  {
    label: '材料名称',
    prop: 'mtlName',
    change: true
  },
  {
    label: '请领量',
    prop: 'reqQty',
    change: true
  },
  {
    label: '已实发量',
    prop: 'actQty',
    change: true,
    backgroundColor: 'true'
  },
  {
    label: '实发量',
    prop: 'avtQty',
  },
  {
    label: '实发日期',
    prop: 'slipDate2',
    type: 'dateSingle',
    width: '120px'
  },
  {
    label: '替代物料编码',
    prop: 'mtlNo2',
    change: true
  },
  {
    label: '用量',
    prop: 'ttlUsage',
    change: true
  },
  {
    label: '已领量',
    prop: 'sendQty',
    change: true
  },
  {
    label: '未领量',
    prop: 'unSendQty',
    change: true
  },
  {
    label: '库存量',
    prop: 'stkQty',
    change: true
  },
  {
    label: '取消',
    type: 'checkbox',
    prop: 'cancelFlag',
  },
])

const tableHeader1 = ref([
  {
    label: '实发日期',
    prop: 'slipDate',
  },
  {
    label: '实发量',
    prop: 'actQty',
  },
])

const tableHeader2 = ref([
  {
    label: '物料编码',
    prop: 'mtlNo2',
  },
  {
    label: '材料名称',
    prop: 'mtlName2',
  },
  {
    label: '材料颜色',
    prop: 'mtlColor2',
  },
  {
    label: '规格',
    prop: 'mtlSpec2',
  },
  {
    label: '单位',
    prop: 'mtlUnit2',
  },
  {
    label: '库存量',
    prop: 'stkQty2',
  },
])

const tableHeader3 = ref([
  {
    label: '领料单号',
    prop: 'slipNo',
  },
  {
    Multistage: true,
    label: '材料替代前',
    children: [
      {
        label: '物料编码',
        prop: 'mtlNo',
      },
      {
        label: '材料名称',
        prop: 'mtlName',
      },
      {
        label: '材料颜色',
        prop: 'mtlColor',
      },
      {
        label: '规格',
        prop: 'mtlSpec',
      },
      {
        label: '单位',
        prop: 'mtlUnit',
      },
      {
        label: '数量',
        prop: 'qty',
      },
    ]
  },
  {
    Multistage: true,
    label: '材料替代后',
    children: [
      {
        label: '物料编码',
        prop: 'mtlNo2',
      },
      {
        label: '材料名称',
        prop: 'mtlName2',
      },
      {
        label: '材料颜色',
        prop: 'mtlColor2',
      },
      {
        label: '规格',
        prop: 'mtlSpec2',
      },
      {
        label: '单位',
        prop: 'mtlUnit2',
      },
      {
        label: '数量',
        prop: 'qty2',
      },
    ]
  },
])

const Launchform = (row: any) => {
  MaterialRequisitionDetailsMethodsParms.value.slipNo = row[0].inputValue
  MaterialRequisitionDetailsMethodsParms.value.lotNo = row[1].inputValue
  MaterialRequisitionDetailsMethodsParms.value.slipDateStart = row[2].dateValue[0]
  MaterialRequisitionDetailsMethodsParms.value.slipDateEnd = row[2].dateValue[1]
  MaterialRequisitionDetailsMethodsParms.value.deptNo = row[3].selectValue.split(' ')[0]
  MaterialRequisitionDetailsMethodsParms.value.deptName = row[3].selectValue.split(' ')[1]
  MaterialRequisitionDetailsMethodsParms.value.slipType = row[4].selectValue.split(' ')[0]
  MaterialRequisitionDetailsMethodsParms.value.mtlTypeNo = row[5].selectValue.split(' ')[0]
  MaterialRequisitionDetailsMethodsParms.value.mtlName = row[6].inputValue
  MaterialRequisitionDetailsMethods()
}

const Launchform1 = (row: any) => {
  ActualInventionTableDateListParms.value.mtlName = row[1].inputValue
  ActualInventionTableDateListParms.value.mtlTypeNo = row[0].selectValue.split(' ')[0]
  substituteMaterialMethods()
}

const Launchform2 = (row: any) => {
  MaterialSubstitutionQueryMethodsParms.value.slipNo = row[0].inputValue
  MaterialSubstitutionQueryMethodsParms.value.mtlName1 = row[1].inputValue
  MaterialSubstitutionQueryMethodsParms.value.mtlName2 = row[2].inputValue
  MaterialSubstitutionQueryMethods()
}

const findData1 = (find: string) => {
  if (find === '置空') {
    clearFormList2()
  }
  if (find === '确认') {
    if (mtlNoValue.value === '') {
      JMessage.warning('请选择需要替代物料的编号')
    } else {
      MaterialSubstitutionProcessingMethods()
      drawer1.value = false
    }
  }
}

const clearFormList1 = () => {
  formList1.value.forEach((item) => {
    if (item.type === 'input') {
      item.inputValue = '';
    }
    if (item.type === 'select') {
      item.selectValue = '';
    }
    if (item.type === 'date') {
      item.dateValue = '';
    }
    // Add other conditions for different form item types
  });

};

const clearFormList2 = () => {
  formList2.value.forEach((item) => {
    if (item.type === 'input') {
      item.inputValue = '';
    }
    if (item.type === 'select') {
      item.selectValue = '';
    }
    // Add other conditions for different form item types
  });
}

const clickNumber = (row: number) => {
  MaterialRequisitionDetailsMethodsParms.value.userType = Number(row)
  MaterialRequisitionDetailsMethods()
}

</script>

<style lang="less" scoped>
h1 {
  font-size: 16px;
}

.mr10 {
  margin-left: 10px;
}
</style>
